﻿@using Microsoft.AspNetCore.Components.Forms

<h2>Form that binds integer</h2>

<form data-enhance name="bind-integer" method="post" @onsubmit="() => _submitted = true" @formname="bind-integer">
    <input type="text" name="Id" value="@(_attemptedValue ?? Id.ToString())" />
    <input id="send" type="submit" value="Send" />
    <AntiforgeryToken />
</form>

@if (_submitted)
{
    var errors = Context.GetErrors("bind-integer", nameof(Id))?.ErrorMessages;
    if (errors == null)
    {
        <p id="pass">Your integer is @Id!</p>
    }
    else
    {
        <p>There were errors:</p>
        <ul id="errors">
            @foreach (var error in errors)
            {
                <li>@error</li>
            }
        </ul>
    }
}
@code {
    bool _submitted = false;
    string _attemptedValue = null;
    IReadOnlyList<FormattableString> _errors;

    [SupplyParameterFromForm(FormName = "bind-integer")] public int Id { get; set; } = 0;

    [CascadingParameter] public FormMappingContext Context { get; set; }

    protected override void OnInitialized()
    {
        _errors = Context.GetErrors("bind-integer", nameof(Id))?.ErrorMessages;
        if (_errors != null)
        {
            _attemptedValue = Context.GetAttemptedValue("bind-integer", nameof(Id));
        }
    }
}
